<?php
namespace app\reservation\model;
use app\common\model\Base;
use app\gym\model\FitnessTrainerSigning;
use app\reservation\model\ArrangeCourse;
use app\publictool\controller\MsgTpl;
use app\circle\model\Circle;
use app\user\model\User;
use app\gym\model\NutritiousMeal;
use think\Validate;
use think\Cache;
use think\Loader;
/**
 * 教练接收到约课的参数
 * [ArrangeCourse description]
 */
class ArrangeCourse extends Base{
  protected $table = 'gym_course';
  protected static $inputData; //教练接受约课
  protected static  $cacheTag='gym_course'; //缓存的名称,关闭使用缓存直接使用false
  protected static  $autoPushCreateTime = true; //自动添加时间
  protected static $publicTool=null;
  protected static $amountStock = [0=>'个',1=>'分钟',2=>'小时'];
  //教练接受约课
 public static function init(){
   parent::init();
   self::$publicTool = Loader::controller('\\app\\publictool\\controller\\PublicTool');
 }

  /**
   * [accept 教练接收约课邀请]
   * @param  array  $input [description]
   * @return [type]        [description]
   */
  public static function accept(){
    $input = self::getInputData();
    $input['fitness_id'] = $input['uuid'];
    $gymInfo = FitnessTrainerSigning::gymFitnessSigningInfo($input);
    $gymId = array_combine(['gym_id'],array_column($gymInfo,'gym_id'));
    $input['gym_id'] = $gymInfo[0]['gym_id'];
    unset($input['uuid']);
    $allowField = ['member_id','fitness_id','gym_id','begin_time','end_time','feeding','create_time','target_section'];
    $lastInsertId ='';
    if(!array_key_exists('member_id',$input) || !array_key_exists('fitness_id',$input) || !array_key_exists('gym_id',$input)){
        abort(-0001,'参数不全不能进行操作请到消息管理中查看并操作！');
    }
    $validate = new Validate(
      [
        'begin_time'=>'require|number', //开始时间
        'end_time'=>'require|number',//结束时间
        'feeding'=>'require|number',//健康食品
        'target_section'=>'require'//本届目标
      ],
      [
        'begin_time.require'=>'开始时间必须!',
        'end_time.require'=>'结束时间必须！',
        'feeding.require'=>'营养餐必须！',
        'begin_time.number'=>'开始时间必须是时间戳！',
        'end_time.number'=>'结束时间必须时间戳！',
        'feeding.number'=>'健康食品的参数只能是数字1或者0',
        'target_section.require'=>'本节目标不能为空'
      ]
    );
    if(!$validate->check($input)){

          abort(-0004,$validate->getError());

    }

    if(empty($input['course_content'])){

        abort(-0003,'必须添加课程内容！');

    }
    $data = new self();
    $value = $input;
    $value['create_time'] = time();
    //健康食品存储的是当前健身房启用的当天时间的健康食品
    if($input['feeding'] == 1){
        //查询当前健身房今天的健康营养食品是什么
        $nCondition = [
          'gym_id'=>$input['gym_id'],
          'which_day'=>date('w',time()),
          'page'=>1,
          'limit'=>1
        ];
        //查询今天营养餐的编号是多少？
        $meal = NutritiousMeal::mealToday($nCondition);
        if(count($meal) < 1){
            $value['feeding'] = 0;
        }else{
            //如果存在营养参的情况下
            $value['feeding'] = $meal[0]['id'];
        }
    }
    $save = $data->data($value)->allowField($allowField)->isUpdate(false)->save();
    if(!$save){
      abort(-0005,'填加课程失败！');
    }
    $lastInsertId = $data->getLastInsID();
    foreach(json_decode($input['course_content'],true) as $val){
        $val['course_id'] = $lastInsertId;
        $val['create_time'] = time();
        $data->table('gym_course_content')->insert($val);
    }
    //不知道是否进行通知
    return [];
  }
  //教练拒绝约课
  public static function refusedTo($input = []){

  }


  /**
   * [MemberFitnessList 会员健身信息的排行，在传入的单个健身房下面，和在传入的多个健身房下面都是可以的]
   * 支持对健身房的筛选
   * 当需要获取多个健身房下面的
   * 会产生临时的新增字段
   * @param array $info [description]
   * @return array 返回排序完成的信息
   */
  public static function memberFitnessList($info=[]){
      $gymId = $info['gym_id'];
      $params = self::sqlParams($info,[
        'order'=>'count(gc.member_id) desc',
        'limit'=>10,
        'page'=>1,
        'field'=>[
            'gc.gym_id',
            'gc.fitness_id',
            'gc.begin_time',
            'gc.end_time',
            'usi.uuid',
            'count(gc.member_id) as when_long',
            'usi.name',
            'usi.nick_name',
            'usi.head_figure'
        ],
      ]);
      self::cacheRefresh();
      if(is_array($gymId)){
          $result = self::where('gc.gym_id','in',$gymId);
      }
      if(is_string($gymId)){
          $result =  self::where('gc.gym_id=\''.$gymId.'\'');
      }
      $result = $result->alias('gc');
      $result = $result->join('__SIGNING_FITNESS_INSTRUCTOR__ sfi','gc.member_id = sfi.member_id AND gc.gym_id = sfi.gym_id AND sfi.status = 1','INNER');
      $result = $result->WhereTime('gc.create_time',$info['week']);
      $result = $result->join('__USER_INFO__ usi','gc.member_id = usi.uuid','INNER')->group('gc.member_id')->order($params['order']);
      $result = $result->limit($params['limit'])->page($params['page']);
      $result = $result->field($params['field']);
      $response = self::infoOfCache($result);
      $userInfo = db('user_info');
      if(!empty($response)){
          foreach($response as &$val){
              $val['fitness_nickname'] = $userInfo->where(['uuid'=>$val['fitness_id']])->find()['nick_name'];
          }
      }
      return $response;
  }



  /**
   * [MemberFitnessList 会员健身信息的排行，在传入的单个健身房下面，和在传入的多个健身房下面都是可以的]
   * 支持对健身房的筛选
   * 当需要获取多个健身房下面的
   * 会产生临时的新增字段
   * @param array $info [description]
   * @return array 返回排序完成的信息
   */
  public static function fitnessListRankings($info=[]){
      $gymId = $info['gym_id'];
      $params = self::sqlParams($info,[
        'order'=>'count(gc.fitness_id) desc',
        'limit'=>10,
        'page'=>1,
        'field'=>[
            'gc.gym_id',
            'gc.fitness_id',
            'usi.uuid',
            'count(gc.fitness_id) as when_long',
            'usi.name',
            'usi.nick_name',
            'usi.head_figure'
        ],
      ]);
      self::cacheRefresh();
      if(is_array($gymId)){
          $result = self::where('gc.gym_id','in',$gymId);
      }
      if(is_string($gymId)){
          $result =  self::where('gc.gym_id=\''.$gymId.'\'');
      }
      $result = $result->alias('gc');
      $result = $result->WhereTime('gc.create_time',$info['week']);
      $result = $result->join('__USER_INFO__ usi','gc.fitness_id = usi.uuid','INNER')->group('gc.fitness_id')->order($params['order']);
      $result = $result->limit($params['limit'])->page($params['page']);
      $result = $result->field($params['field']);
      $response = self::infoOfCache($result);
      return $response;
  }

  /**
   * [获取会员最近一次未上课的时间]
   * @return [type] [description]
   */
  public static function getMemberLatleyCourse( $uuid ){
      $where = ["member_id"=>$uuid];
      $result = function($where){
        return self::where($where)->field(["begin_time","end_time"])->whereTime("begin_time",">",time());
      };
      $count = $result($where)->count();
      if($count < 1){
        return 0;
      }
      return $result($where)->find();
  }

  /**
   * [aboutClassObject 统计会员剩余课时的对象]
   * @param  array  $info [设置筛选项目]
   * @return [Object]       [返回对象]
   */
  public static function aboutClassObject($info=[]){
      $where = ['co.fitness_id'=>$info['fitness_id']];
      $field = [
        'co.id', //约课信息的id主要用于调用约课信息的详细信息
        'co.fitness_id', //教练的id
        'co.member_id', //会员的id
        'co.begin_time', //开始的时间
        'co.end_time', //结束的时间
        'co.create_time',//创建时间
        'usi.name',//约课会员的名称
        'usi.nick_name',//约课会员的昵称
        'usi.phone_num',//约课会员的手机号码
        'usi.gender',//约课会员的性别
        'usi.head_figure',//约课会员的头像信息
      ];
      $result = self::where($where)->alias('co');
      $count  = '';
      switch($info['condition']){
          //
          case 'today':
            //查询今日约课的数量
            $beginTime = strtotime(date('Y-m-d',time()));
            $endTime = strtotime('+1 Day',$beginTime)-1;
          break;
          case 'tomorrow':
            //查询明日约课的数量
            $beginTime = strtotime('+1 Day',strtotime(date('Y-m-d',time())));
            $endTime = strtotime('+1 Day',$beginTime)-1;
          break;
          default:
          abort(-34,'参数错误！');
      }
      $result->where('begin_time','>=',$beginTime);
      $result->where('begin_time','<=',$endTime);
      $result->join('__USER_INFO__ usi','co.member_id = usi.uuid','INNER')->field($field);
      return $result;
  }

  /**
   * [coustomSort 自定义排序方法]
   * @return [type] [description]
   */
  protected static function coustomSort($a,$b){

      return $a['when_long'] > $b['when_long']? 0:1;

  }

  /**
   * [aboutClassInfo 约课信息查询]
   * 其中会产生的信息是
   * 1. 当前约课的会员信息列表
   * @return [array] [返回的必要数据]
   */
  public static function aboutClassInfo($info=[]){
    if(!array_key_exists('fitness_id', $info)){
        $info['fitness_id'] = $info['uuid'];
        unset($uuid);
    }
    $result = self::aboutClassObject($info);
    $count = self::aboutClassObject($info);
    $first = self::aboutClassObject($info);
    $last = self::aboutClassObject($info);
    //取出会员的上一次记录
    $response['list']= self::infoOfCache($result); //今日约课的会员列表
    $response['count'] = $count->count(); //今日约课的总数量
    $response['surplus'] =0; //surplus
    $response['first'] = 0; //今天最早的
    $response['last'] = 0;//今天最晚的
    $firstTime =$first->order('begin_time asc')->limit(1)->field('begin_time')->find();
    $lastTime = $last->order('begin_time desc')->limit(1)->field('begin_time')->find();
    if(!is_null($firstTime)){
          $response['first'] = $firstTime->getAttr('begin_time'); //今天最早的
    }
    if(!is_null($lastTime)){
          $response['last'] = $lastTime->getAttr('begin_time'); //今天最早的
    }

    switch($info['condition']){
        //
        case 'today':
          //查询今日约课的数量
          $beginTime = strtotime(date('Y-m-d',time()));
        break;
        case 'tomorrow':
          //查询明日约课的数量
          $beginTime = strtotime('+1 Day',strtotime(date('Y-m-d',time())));
        break;
        default:
        abort(-34,'参数错误！');
    }
    $lastCourse = self::lastCourse(array_column($response['list'],'member_id'),$beginTime);
    //遍历数组合并内容
    foreach($response['list'] as $key => $val){
          foreach($lastCourse as $value){
              if($value['member_id'] == $val['member_id']){
                   $response['list'][$key] = array_merge($val,$value);
              }
          }
    }
    return $response;
  }

  /**
   * [gymCourse 今日约课的统计]
   * @return [type] [description]
   */
  public static function gymCourse($info=[]){
      if(array_key_exists('gym_id', $info)){
            if(is_array($info['gym_id'])){
                $result = self::where('gym_id','in',$info['gym_id']);
            }else{
                $result = self::where('gym_id','in',$info['gym_id']);
            }
      }else{
          abort(-20,'参数错误！');
      }
      //设置筛选时间
      if(!array_key_exists('date',$info)){
           $result->whereTime('create_time','today');
      }else{
           $result->whereTime('create_time',$info['date']);
      }
      return $result->count();
  }

  /**
   * [lastCourse 会员上一次的约课信息]
   * @return [type] [会员上一次的约课信息]
   */
  public static function lastCourse($memberId=[],$courseTime,$condition='last'){
      if(is_array($memberId)){
          $result = self::where('member_id','in',$memberId);
      }else{
          $result = self::where('member_id','=',$memberId);
      }
      $result->where('begin_time','<',$courseTime);
      switch($condition){
          case 'last':
          $result->field(['MAX(begin_time) as last_course','feeding as last_course_feeding','member_id']);
          break;
          default:
          abort(-45,'参数错误！');
}
    $response = self::infoOfCache($result);
    return $response;
  }


  public static function info( $info = [] ){

      if(array_key_exists('uid',$info)){

          $where = ['member_id'=>$info['uid']];

      }
      elseif(array_key_exists('uuid',$info)){

          $where = ['member_id'=>$info['uuid']];

      }

      $sqlQuery = self::sqlParams($info,[
        'limit'=>10,
        'field'=>true,
        'page'=>1,
        'order'=>'create_time desc',
      ]);
      $sqlResult = function($where){
        //gym_nutritious_meal
          $result =  self::where($where);
          return $result;
      };
      $count  = $sqlResult($where)->count();
      $result = self::infoOfCache($sqlResult($where)->page($sqlQuery["page"])->limit($sqlQuery["limit"])->order($sqlQuery["order"]));
      if($count < 1){
          $result = [];
      }else{
        $result = collection($result)->toArray();
        foreach($result as &$val){
            $resl = array_column(db("course_content")->field(["ev.title"])->where(["course_id"=>$val["id"]])->alias("cc")->join("__EXERCISE_VENT__ ev","cc.exercise_vent_id = ev.id")->select(),"title");
            $val['title'] = implode("，",$resl);
        }
      }
      return MsgTpl::createListTpl($result,$count,$sqlQuery['limit'],$sqlQuery['page']);
  }

  /**
  *查询会员的约课信息
  *查询会员约约课的详细信息
  */
  public static function courseInfo($info = [] ){
      if(!array_key_exists('id',$info)){
          //通过会员和教练的编号进行查询
          array_key_exists('fitness_id',$info)?:$info['fitness_id'] = $info['uuid'];
          $where = ['ac.member_id'=>$info['member_id'],'ac.fitness_id'=>$info['fitness_id']];
      }else{
          //通过id进行查询
          $where = ['ac.id'=>$info['id']];
      }
      $sqlQuery = self::sqlParams($info,[
        'field'=>[
          'ac.*',
          'nm.ingredients',
          'nm.picture',
          'nm.nutrition',
          'usi.head_figure as fitness_head_figure',
          'usi.nick_name as fitness_nick_name',
          'usi.name as fitness_name',
          'gi.store_title',
        ],
        'order'=>'ac.create_time desc',
      ]);
      $sqlResult = function($where,&$sqlQuery){
          $result = self::where($where)->alias('ac');
          //gym_nutritious_meal
          $result->join('__NUTRITIOUS_MEAL__ nm','ac.feeding = nm.id','LEFT');
          $result->join('__GYM_INFO__ gi','ac.gym_id = gi.unique_id','INNER');
          $result->join('__USER_INFO__ usi','ac.fitness_id = usi.uuid','INNER');
          if(Circle::where(['index_id'=>$where['ac.id']])->count() > 0){
             $result->join('__CIRCLE__ ci','ac.id = ci.index_id','LEFT');
             array_push($sqlQuery['field'],'ci.id as circle_id');
          }
          $result->field($sqlQuery['field']);
          return $result;
      };
      $count = $sqlResult($where,$sqlQuery)->count();
      if($count > 0){
            //获取的就是单条数据
            $result = self::infoOfCache($sqlResult($where,$sqlQuery)->order($sqlQuery['order']),true)[0];
            $userInfo = User::info(['uuid'=>$result['member_id']]);
            $result['course_content'] = CourseContent::info(['course_id'=>$result['id']]);
            $result['member_head_figure'] = $userInfo['head_figure'];
            $result['member_nick_name'] = $userInfo['nick_name'];
            $result['member_name']=$userInfo['name'];
            $amountStock = self::$amountStock;
            //如果存在朋友圈编号的话那么进行插入操作
            if(array_key_exists('circle_id',$result)){
              $thumb = new \app\circle\model\ThumbUp();
              $result['thumb_up_queue'] = $thumb::info(10,1,$result['circle_id']);
            }
            $keyUp = 1;
            $courseContent = '';

            if(count($result['course_content']) > 0){
                foreach($result['course_content'] as  $key => $val){
                    list($title,$amount,$length,$repeat) = [$val['title'],$amountStock[$val['amount']],$val['length'],$val['repeat']];
                    if($keyUp == count($result['course_content'])){
                      $courseContent .= $keyUp.'.'.$title.$length.'组，每组'.$repeat.$amount;
                    }else{
                      $courseContent .= $keyUp.'.'.$title.$length.'组,每组'.$repeat.$amount.', \n';
                    }
                    $keyUp++;
                }
                $result['course_content'] = $courseContent;
            }
      }else{
          abort('查询的课程信息不存在！');
      }
      //返回最后的数据
      return $result;
  }



}
